<template>

    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades">订单列表</i>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">

                <el-date-picker v-model="query.deadLine" placeholder="订单日期" type="month" class="handle-search mr10" ></el-date-picker>
                <el-input v-model="query.company" placeholder="公司名称" class="handle-search mr10"></el-input>
                <el-select v-model="query.product" value-key="id"  placeholder="产品型号" class="handle-search mr10" >
                    <el-option
                            v-for="item in productList"
                            :key="item.id"
                            :label="item.productModel"
                            :value="item">
                    </el-option>
                </el-select>

                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <!--        增加记录        -->
                <el-button type="primary" icon="el-icon-zoom-in" @click="handleAdd">添加</el-button>
                <el-button icon="el-icon-download" @click="exportExcel">导出</el-button>
                <el-button type="danger" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <!--<el-button icon="el-icon-upload" @click="handleImport">导入</el-button>-->
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    id="out-table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column type="index" width="55" align="center" label="序号"></el-table-column>
                <el-table-column prop="orderNum" align="center" label="订单号" ></el-table-column>
                <el-table-column prop="product.productModel" align="center" label="加工产品" width="110"></el-table-column>
                <el-table-column prop="number" align="center" label="数量" width="80"></el-table-column>
                <el-table-column prop="createDate" align="center" label="下单日期" width="130px"  sortable ></el-table-column>
                <el-table-column prop="deadLine" align="center" label="交货日期"  width="130px" sortable></el-table-column>
                <el-table-column prop="status" align="center" :formatter="statusFormat" width="100px" label="状态"></el-table-column>
                <el-table-column prop="company" align="center" label="客户" ></el-table-column>
                <el-table-column label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-check"
                                class="green"
                                @click="submit(scope.row)"
                        >交货</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit-outline"
                                class="yellow"
                                @click="addException(scope.row)"
                        >异常</el-button>
                    </template>
                </el-table-column>

            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                        align="center"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" >
            <el-form ref="form" :model="form" :rules="rules" label-width="95px">

                <el-form-item label="订单号" prop="orderNum" >
                    <el-input v-model="form.orderNum" class="handle-input mr10" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="加工产品" prop="product" >
                    <el-input v-model="form.product.productModel" class="handle-input mr10" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="加工数量" prop="number" >
                    <el-input v-model="form.number" class="handle-input mr10" ></el-input>
                </el-form-item>

                <el-form-item label="下单日期" prop="createDate" >
                    <el-date-picker
                            v-model="form.createDate"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="交货日期" prop="deadLine" class="handle-input mr10" >
                    <el-date-picker
                            v-model="form.deadLine"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="客户" prop="company"  >
                    <el-input v-model="form.company" class="handle-input mr10" :disabled="true" ></el-input>
                </el-form-item>


            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加弹出框 -->
        <el-dialog title="添加" :visible.sync="addVisible" width="30%" >
            <el-form ref="form" :model="form" :rules="rules" label-width="95px">

                <el-form-item label="订单号" prop="orderNum" >
                    <el-input v-model="form.orderNum" class="handle-input mr10" ></el-input>
                </el-form-item>

                <el-form-item label="加工产品" prop="product" >
                    <el-select v-model="form.product" value-key="id" class="handle-input mr10" >
                        <el-option
                                v-for="item in productList"
                                :key="item.id"
                                :label="item.productModel"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="加工数量" prop="number" >
                    <el-input v-model="form.number" class="handle-input mr10" ></el-input>
                </el-form-item>

                <el-form-item label="下单日期" prop="createDate" >
                    <el-date-picker
                            v-model="form.createDate"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="交货日期" prop="deadLine" class="handle-input mr10" >
                    <el-date-picker
                            v-model="form.deadLine"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>


                <el-form-item label="客户" prop="company"  >
                    <el-input v-model="form.company" class="handle-input mr10" ></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
        <!--添加异常订单-->
        <el-dialog title="添加异常" :visible.sync="exceptionVisible" width="30%" >
            <el-form ref="exceptionForm" :model="exceptionForm"  label-width="95px">

                <el-form-item label="订单号" prop="orderNum" >
                    <el-input v-model="exceptionForm.orderNum" class="handle-input mr10" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="加工产品" prop="product" >
                    <el-select v-model="exceptionForm.product" value-key="id" class="handle-input mr10" :disabled="true">
                        <el-option
                                v-for="item in productList"
                                :key="item.id"
                                :label="item.productModel"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="客户" prop="company"  >
                    <el-input v-model="exceptionForm.company" class="handle-input mr10" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="描述" prop="describe" >
                    <el-input type="textarea" v-model="exceptionForm.describe" style="height: 50px" class="handle-input mr10" ></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="exceptionVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveException">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
    import FileSaver from 'file-saver'
    import XLSX from 'xlsx'
    export default {
        name: "order",
        data() {
            return {
                query: {
                    company:'',
                    product:{
                        id:0,
                        productModel: ""
                    },
                    pageIndex: 1,
                    pageSize: 10
                },

                fileList:{},
                productList:[],
                tableData: [],
                multipleSelection: [],
                exceptionVisible:false,
                addVisible: false,
                editVisible: false,
                importVisible: false,
                pageTotal: 0,
                flag:0,
                form: {
                    product:""
                },
                exceptionForm: {
                    product:""
                },
                idx: -1,

                rules: {
                    orderNum: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
                    product: [{ required: true, message: '请输入加工产品', trigger: 'blur' }],
                    company: [{ required: true, message: '请输入客户', trigger: 'blur' }],
                },

            };

        },
        created() {

            this.getProduct();
            this.handleSearch();

        },
        methods: {
            //交货
            submit(row){
                this.$axios.post('/api/orders/submit',row).then(res=>{
                    if (res.data.code!=="200"){
                        this.$message.error(res.data.message);
                    } else {
                        this.$message.success(res.data.message);
                    }
                })
            },
            //添加异常
            addException(row){
                this.exceptionVisible=true;
                this.exceptionForm=row;
            },
            //保存异常
            saveException(){
                this.exceptionVisible=false;
                let param = {
                    orderId:this.exceptionForm.id,
                    describe:this.exceptionForm.describe,
                };
                this.$axios.post('/api/orders/addException',param).then(res=>{
                    if (res.data.code!=="200"){
                        this.$message.error(res.data.message);
                    } else {
                        this.$message.success(res.data.message);
                    }
                })
            },
            //获取产品
            getProduct(){
                this.$axios.get('/api/product/selectAll').then((res) => {
                    if (res.data.code!=="200"){
                        this.$message.error(res.data.message);
                    } else {
                        this.productList=res.data.data;
                    }
                })
            },
            //批量删除
            delAllSelection(){
                const length = this.multipleSelection.length;
                if (length===0){
                    this.$message.warning("请选择要删除的产品");
                }else {

                    this.$confirm('确定要删除吗？', '提示', {
                        type: 'warning'
                    })
                        .then(() => {
                            for (let i = 0; i < length; i++) {

                                this.$axios.post('/api/orders/deleteOrder', this.multipleSelection[i]).then((res) => {
                                    if (res.data.code !== "200") {
                                        this.flag = 2;
                                    }
                                });
                                this.flag = 1;
                            }

                            if (this.flag === 1) {
                                this.$message.success("删除成功");
                            } else {
                                this.$message.error("删除失败");
                            }

                        })
                        .catch(() => {
                            this.$message.error("删除失败");
                        }).finally(()=>{
                            this.handleSearch();
                        });
                }
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            // 编辑操作
            handleEdit(index, row) {

                this.idx = index;
                this.form = row;
                this.editVisible = true;
                console.log(this.form);
            },
            // 删除操作
            handleDelete(row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {

                        this.$axios.post('/api/orders/deleteOrder',row).then(res=>{
                            if(res.data.code==="200"){
                                this.$message.success(res.data.message);
                                this.handleSearch();
                            }else {
                                this.$message.error(res.data.message);
                            }

                        })
                    })
                    .catch(() => {
                        this.$message.error("删除失败");
                    });
            },
            // 保存编辑
            saveEdit() {
                console.log(this.form);

                this.editVisible = false;
                this.$axios.post('/api/orders/editOrder',this.form).then(res=>{
                    if(res.data.code==="200"){
                        this.$message.success(res.data.message);

                    }else {
                        this.$message.error(res.data.message);
                    }

                }).catch(
                    error=>{
                        this.$message.error("修改失败");
                    }
                ).finally(()=>{
                    this.handleSearch();
                });

            },
            //返回成功的钩子
            handleSuccess(response, file, fileList){

                this.$message.success("导入成功");
                this.$refs.upload.clearFiles();
                this.importVisible=false;
                this.getData();
            },
            //返回失败的钩子
            handleError(err, file, fileList){
                this.$message.error("导入失败");
                this.$refs.upload.clearFiles();
                this.importVisible=false;
                this.getData();
            },

            //tableData 翻译status
            statusFormat(row, column){

                if (row.status === '0') {
                    return '未交货'
                } else if (row.status === '1') {
                    return '已交货'
                } else if (row.status === '-1') {
                    return '异常'
                }
            },

            //选择两个文件时报错
            handleExceed(files, fileList) {
                this.$message.warning('请将已选择文件删除后，再重新选择文件');
            },
            //显示上传文件窗口
            handleImport(){
              this.importVisible=true
            },
            //提交上传文件
            submitUpload(){
                if(this.query.produceDate===''){
                    this.$message.warning("请选择订单时间")
                }else if (this.$refs.upload.uploadFiles.length===0) {
                    this.$message.warning("请选择要上传的文件")
                }else {
                    this.$refs.upload.submit();
                }
            },
            // 保存添加
            saveAdd() {
                this.$refs.form.validate(valid => {
                    if (valid) {

                        console.log(this.form);
                        this.addVisible = false;
                        this.$axios.post('/api/orders/addOrder',this.form).then(res=>{
                            if(res.data.code==='200'){
                                this.$message.success(res.data.message);

                            }else {
                                this.$message.error(res.data.message);
                            }
                        }).catch(
                            error=>{
                                this.$message.error("添加失败");
                            }
                        ).finally(()=>{
                            this.handleSearch();
                        });


                    }
                    else {
                        this.$message.error('请检查输入');
                        console.log('error submit!!');
                        return false;
                    }
                })
            },
            // 触发搜索按钮
            handleSearch() {
                this.$axios({
                    method:"get",
                    url:"/api/orders/search",
                    params:{

                        deadLine:this.query.deadLine,
                        company:this.query.company,
                        product:this.query.product.id
                    }
                }).then(res =>{
                    if (res.data.code!=='200') {
                        this.$message.error(res.data.message);
                    }else {
                        this.pageSplit(res.data.data);
                    }
                });

            },
            //分页
            pageSplit(data){
                this.pageTotal=data.length;
                let start= (this.query.pageIndex-1)*this.query.pageSize;
                let end = this.query.pageIndex*this.query.pageSize<this.pageTotal?this.query.pageIndex*this.query.pageSize:this.pageTotal;
                this.tableData=[];
                for (let i=start;i<end;i++){
                    this.tableData[i-start]=data[i];
                }
            },

            //添加操作
            handleAdd() {
                this.addVisible = true;
            },
            // 分页导航
            handlePageChange(val) {

                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },

            //导出计划
            exportExcel () {
                /* out-table关联导出的dom节点  */
                var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'));
                /* get binary string as output */
                var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                try {
                    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '订单列表.xlsx')
                } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
                return wbout
            }

        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-search{
        width: 130px;
        display: inline-block;
    }

    .handle-input {
        width: 200px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .green {
        color: #67C23A;
    }
    .yellow{
        color: #f0c78a;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

</style>